package com.lsj.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.annotation.SessionScope;

import java.util.Map;

@Component
@SessionScope
public class TokenTask {

    @Autowired
    RestTemplate restTemplate;
    private String access_token = "";
    private String refresh_token="";

    public String getData(String code){
        if(StringUtils.isEmpty(access_token) && !StringUtils.isEmpty(code)){
            MultiValueMap<Object, Object> map = new LinkedMultiValueMap<>();
            map.add("code",code);
            map.add("client_id","appService");
            map.add("client_secret","123");
            map.add("grant_type","authorization_code");
            map.add("redirect_uri","http://localhost:8082/index.html");
            Map<String,String> resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, Map.class);
            access_token = resp.get("access_token");
            refresh_token = resp.get("refresh_token");
            return loadDataFromServer();
        }else{
            return loadDataFromServer();
        }
    }

    public String loadDataFromServer(){
        try{
            System.out.println("从资源服务器加载数据");
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization","Bearer "+access_token);
            HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
            ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8081/admin/hello", HttpMethod.GET, httpEntity, String.class);
            String msg = entity.getBody();
            return msg;
        }catch (RestClientException e){
            return "未认证";
        }

    }

    @Scheduled(cron = "0 55 0/1 * * ?")
    public void tokenRefreshTask(){
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id","appService");
        map.add("client_secret","123");
        map.add("grant_type","refresh_token");
        Map<String,String> resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, Map.class);
        access_token = resp.get("access_token");
        refresh_token = resp.get("refresh_token");
    }

}
